/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.admin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import net.risesoft.risebi.collection.commons.constants.SystemConstants;
import net.risesoft.risebi.collection.model.Application;
import net.risesoft.risebi.collection.model.Catalog;
import net.risesoft.risebi.collection.model.Department;
import net.risesoft.risebi.collection.model.Employee;
import net.risesoft.risebi.collection.model.Level;
import net.risesoft.risebi.collection.model.Module;
import net.risesoft.risebi.collection.model.Service;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.model.UserSO;
import net.risesoft.risebi.collection.service.ApplicationManager;
import net.risesoft.risebi.collection.service.CatalogManager;
import net.risesoft.risebi.collection.service.DbMetaDataManager;
import net.risesoft.risebi.collection.service.DepartmentManager;
import net.risesoft.risebi.collection.service.DynaBeanManager;
import net.risesoft.risebi.collection.service.EmployeeManager;
import net.risesoft.risebi.collection.service.LevelManager;
import net.risesoft.risebi.collection.service.RoleMemberManager;
import net.risesoft.risebi.collection.service.ServiceManager;
import net.risesoft.risebi.collection.service.SoTypeManager;
import net.risesoft.risebi.collection.service.UserManager;
import net.risesoft.risebi.collection.service.UserSOManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.exception.SameEntityException;
import net.risesoft.risebi.commons.struts2extension.Trimable;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.risesoft.risebi.commons.util.PropsUtil;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.dao.DataIntegrityViolationException;

import com.opensymphony.xwork2.ActionInvocation;

/**
 *
 * @author <a href="mailto: chenjian@risesoft.net">陈健</a>
 * @version $Revision$
 * 
 */
@Namespace("/admin/OrgManageAction")
public class OrgManageAction extends BaseAction implements Trimable{	
	private static final long serialVersionUID = 6562223988169157130L;	
	private static Log log = LogFactory.getLog(OrgManageAction.class);
	
	private DbMetaDataManager dbMetaDataManager;
	private DepartmentManager departmentManager;
	private EmployeeManager employeeManager;
	private CatalogManager catalogManager;
	private DynaBeanManager dynaBeanManager;
	private UserManager userManager;
	private UserSOManager userSOManager;
	private SoTypeManager soTypeManager;
	private LevelManager levelManager;
	private ApplicationManager applicationManager;
	private ServiceManager serviceManager;
	
	private Department department;
	private Employee employee;
	private String accounts;
	private User user;

	private HashMap<String,Object> dynaBean;

	private String field; //Ext.ux.plugins.RemoteValidator
	private String value; //Ext.ux.plugins.RemoteValidator
	private String serviceGuid = "";	
	
	/**
	 * 业务管理员开户界面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value="prepareOpenManageUserAccount",
			results={@Result(name="success", location="/admin/user/openAccount4employee.jsp")}
	)
	public String prepareOpenManageUserAccount() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareOpenAccount4so",
			results={@Result(name="success", location="/admin/user/openAccount4so.jsp")}
	)
	public String prepareOpenAccount4so() throws Exception {
		return SUCCESS;
	}

	@Action(value="prepareOpenAccount4catalog",
			results={@Result(name="success", location="/admin/user/openAccount4catalog.jsp")}
	)
	public String prepareOpenAccount4catalog() throws Exception {	
		ArrayList newList = new ArrayList();		
		List<Application> lst = applicationManager.getAppsByServiceWithPermission(this.getDefaultService().getGuid(), this.getSessionUser());
		for(Application a : lst){
			Map map = new  HashMap();	
			map.put("guid", a.getGuid());
			map.put("name", a.getChineseName());
			newList.add(map);
		}
		
		this.json = JSONUtil.getJsonString(null, null, newList);			
		return SUCCESS;
	}

	@Action(value="prepareEditUser4Catalog",
			results={@Result(name="success", location="/admin/user/edituser4catalog.jsp")}
	)
	public String prepareEditUser4Catalog() throws Exception {
		Catalog catalog = (Catalog)catalogManager.getObject(Catalog.class, this.node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		dynaBean = (HashMap<String, Object>)dynaBeanManager.getObject(tableName, this.nodeInstance);
		
		ArrayList al = new ArrayList();	
		for(Object prop : dynaBean.keySet().toArray()){
			LazyDynaBean ldb = new  LazyDynaBean();	
			ldb.set("name", (String)prop);
			if(dynaBean.get(prop)==null){
				ldb.set("value", (String)prop+": null");
			}else{
				ldb.set("value", (String)prop+": "+dynaBean.get(prop).toString());
			}			
			al.add(ldb);
		}
		this.json = JSONUtil.getJsonString(null, null, al);	
		
		return SUCCESS;
	}

	@Action(value="prepareDepartmentList4ServiceUser",
			results={@Result(name="success", location="/admin/organize/departmentList4ServiceUser.jsp")}
	)
	public String prepareDepartmentList4ServiceUser() throws Exception {
		return SUCCESS;
	}

	@Action(value="prepareDepartmentList4SystemUser",
			results={@Result(name="success", location="/admin/organize/departmentList4SystemUser.jsp")}
	)
	public String prepareDepartmentList4SystemUser() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareDepartmentEdit",
			results={@Result(name="success", location="/admin/organize/departmentEdit.jsp")}
	)
	public String prepareDepartmentEdit() throws Exception {
		this.department = (Department)departmentManager.getObject(Department.class, this.node);
		
		return SUCCESS;
	}
	
	@Action(value="prepareDepartmentAdd",
			results={@Result(name="success", location="/admin/organize/departmentEdit.jsp")}
	)
	public String prepareDepartmentAdd() throws Exception {
		this.department = new Department();
		this.department.setParentGuid(this.node);
		this.department.setGuid(new GUID().toString(32));		
		//this.department.setServiceGuid(this.serviceGuid);
		return SUCCESS;
	}
	
	@Action(value="prepareDepartmentIndex",
			results={@Result(name="success", location="/admin/organize/departmentIndex.jsp")}
	)
	public String prepareDepartmentIndex() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareEmployeeGrid",
			results={@Result(name="success", location="/admin/organize/employeeGrid.jsp")}
	)
	public String prepareEmployeeGrid() throws Exception {
		try{
			List<Level> lst = levelManager.getObjects(Level.class);
			this.json = JSONUtil.getJsonString("include","guid,parentGuid,name,code,path",lst);
		}catch(Exception e){
			this.json = "[]";
		} 
		
		return SUCCESS;
	}

	/**
	 * 前往开户用户管理界面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value="prepareUserManage",
			results={@Result(name="success", location="/admin/user/usermanage.jsp")}
	)
	public String prepareUserManage() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareEditUserPassword",
			results={@Result(name="success", location="/admin/user/editUserPassword.jsp")}
	)
	public String prepareEditUserPassword() throws Exception {
		user = (User)userManager.getObject(User.class, this.getSessionUser().getGuid());
		
		return SUCCESS;
	}
	
	/**
	 * 前往修改开户用户界面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value="prepareEditUser",
			results={@Result(name="success", location="/admin/user/edituser.jsp")}
	)
	public String prepareEditUser() throws Exception {
		if("employee".equals(this.source)){
			user = (User)userManager.getUserByEmployeeGuid(this.node);
		}else if("so".equals(this.source)){
			user = (User)userManager.getUserBySoInstanceGuid(this.node, this.json);
		}else{
			user = (User)userManager.getObject(User.class, user.getGuid());
		}
		
		this.json = JSONUtil.getJsonString("include", "realName,name,tabIndex,userType,enabled,authentication_type,openAccountType,sex,email,phone,mobile,ip,guid,password", user);
			
		return SUCCESS;
	}
	
	/**
	 * 获得业务管理员，是有权限的
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value="getAllEmployee")
	public String getAllEmployee() throws Exception {
//		TODO: 是有权限的
		if(employee==null)
			employee = new Employee();
		if(limit==0){
			String ps = PropsUtil.getProperty("OrgManageAction_getAllEmployee");
			if(ps==null){
				//ps = PropsUtil.getProperties(SystemConstants.REPORT_PAGINGSIZE);
				ps = "10";
			}
			limit = Integer.valueOf(ps); 
		}
			
		Map map = employeeManager.getAllEmployee(employee, start, limit);
		int count = (Integer) map.get("count");
		List list = (List) map.get("list");
		
		this.json = JSONUtil.getJsonString("exclude", "department,level", map);
		
		return AJAX;
	}

	/**
	 * 修改用户
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value="editUser",
			results={@Result(name="success", type="transfer",params={"method","callOpenerFunction"})}
	)
	public String editUser() throws Exception {
//		排重
		String sql = "select count(*) from User a where (a.name='"+user.getName()+"' or a.realName='"+user.getRealName()+"') and a.guid<>'"+user.getGuid()+"'";
		Integer count = userManager.getCount(sql);
		if(count>0)
			throw new SameEntityException();
		
		if(log.isDebugEnabled()){
			log.debug("开始修改开户用户的信息，修改的用户Guid："+user.getGuid());
		}
		
		User oldUser = (User) userManager.getObject(User.class, user.getGuid());
		oldUser.setRealName(user.getRealName());
		oldUser.setName(user.getName());
		oldUser.setEnabled(user.getEnabled());
		oldUser.setTabIndex(user.getTabIndex());
		
		userManager.saveObject(oldUser);
		
		if(log.isDebugEnabled()){
			log.debug("成功修改开户用户的信息，修改的用户Guid："+user.getGuid());
		}
		
		dynaMethod = "afterModifyUser()";
		return SUCCESS;
	}
	
	@Action(value="editUser4Employee")
	public String editUser4Employee() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			JSONObject jsonObject = JSONObject.fromObject( this.json );
			User user = (User)JSONObject.toBean(jsonObject, User.class);
			//排重
			String sql = "select count(*) from User a where a.realName='"+user.getRealName()+"' and a.guid<>'"+user.getGuid()+"'";
			Integer count = userManager.getCount(sql);
			if(count>0){
				throw new Exception();
			}else{
				if(user.getAuthentication_type()<1){
					user.setAuthentication_type(1);
				}
				if(user.getOpenAccountType()<1){
					user.setOpenAccountType(1);
				}
				if(user.getSex()<1){
					user.setSex(1);
				}

				User oldUser = (User) userManager.getObject(User.class, user.getGuid());
				oldUser.setRealName(user.getRealName());
				oldUser.setName(user.getName());
				oldUser.setEnabled(user.getEnabled());
				oldUser.setAuthentication_type(user.getAuthentication_type());
				oldUser.setOpenAccountType(user.getOpenAccountType());
				oldUser.setSex(user.getSex());
				oldUser.setEmail(user.getEmail());
				oldUser.setPhone(user.getPhone());
				oldUser.setMobile(user.getMobile());
				oldUser.setPassword(user.getPassword());
				
				userManager.saveObject(oldUser);
			}			
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="editUserPassword")
	public String editUserPassword() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			User oldUser = (User)userManager.getObject(User.class, user.getGuid());
		
			if(!oldUser.getPassword().equals(user.getPassword())){
				ldb.set("success", false);
				ldb.set("reason", "输入的用户旧密码不正确！");			
				this.json = JSONObject.fromObject(ldb).toString();
				return AJAX;
			}
			
			if(node.equals(user.getInitialPassword())){
				ldb.set("success", false);
				ldb.set("reason", "密码过于简单，请重新输入新密码！");
				this.json = JSONObject.fromObject(ldb).toString();
				return AJAX;
			}
			
			oldUser.setPassword(this.node);
			userManager.saveObject(oldUser);
			
			ldb.set("success", true);
			ldb.set("reason", "修改用户密码成功！");			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}
	
	@Action(value="editUser2")
	public String editUser2() throws Exception { 
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if(user.getAuthentication_type()<1){
				user.setAuthentication_type(1);
			}
			if(user.getOpenAccountType()<1){
				user.setOpenAccountType(1);
			}
			if(user.getSex()<1){
				user.setSex(1);
			}

			User oldUser = (User) userManager.getObject(User.class, user.getGuid());
			oldUser.setRealName(user.getRealName());
			oldUser.setName(user.getName());
			oldUser.setEnabled(user.getEnabled());
			oldUser.setAuthentication_type(user.getAuthentication_type());
			oldUser.setOpenAccountType(user.getOpenAccountType());
			oldUser.setSex(user.getSex());
			oldUser.setEmail(user.getEmail());
			oldUser.setPhone(user.getPhone());
			oldUser.setMobile(user.getMobile());
			oldUser.setPassword(user.getPassword());
		
			userManager.saveObject(oldUser);
			
			ldb.set("success", true);
			ldb.set("reason", "修改用户信息成功！");
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	/**
	 * 获得开户用户
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value="getAllUser")
	public String getAllUser() throws Exception {
		if(user==null)
			user = new User();
		if(limit==0){
			String ps = PropsUtil.getProperty("OrgManageAction_getAllUser");
			if(ps==null){
				//ps = PropsUtil.getProperty(SystemConstants.REPORT_PAGINGSIZE);
				////	默认分页大小
				//public static final String REPORT_PAGINGSIZE = "pagingSize";
				ps = "10";
			}
			limit = Integer.valueOf(ps); 
		}
		
		if(log.isDebugEnabled()){
			log.debug("准备开始获取开户用户的列表......");
		}
			
		Map map = userManager.getAllUser(user, "u", "", start, limit);

		if(log.isDebugEnabled()){
			log.debug("结束获取开户用户的列表");
		}
		
		this.json = JSONUtil.getJsonString("include", "count,list,guid,name,realName,password,authentication_type,email,sex,phone,mobile,enabled,tabIndex,userType,openAccountType,ip", map);
		
		return AJAX;
	}
	
	/**
	 * @see net.risesoft.commons.struts2extension.Trimable#afterTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public void afterTrim(ActionInvocation invocation) {
		
	}

	/**
	 * @see net.risesoft.commons.struts2extension.Trimable#preTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public boolean preTrim(ActionInvocation invocation) {
		return true;
	}
	
	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		Date date1 = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");  
		log.info(sdf.format(DateUtils.addDays(date1, 360))) ;

		try{
			if("jsonUsers4catalog".equalsIgnoreCase(this.whichJson)){
				List<User> lst = userManager.find("from User u where u.so_instance_guid='"+this.nodeInstance+"'");
				this.json = JSONUtil.getJsonString("exclude","employee,roleMembers,roles,departments",lst);
			}else if("jsonDepartment4SystemUser".equalsIgnoreCase(this.whichJson)){
				List jsonList = new ArrayList();
				if(this.active_node_id==null || this.active_node_id.trim().length()==0){
					List<Service> lst = serviceManager.getServicesWithPermission(this.getSessionUser());					
					for(Service s : lst){
						Map map = new HashMap();
						map.put("guid", s.getGuid());
						map.put("parentGuid", "");
						map.put("serviceGuid", s.getGuid());
						map.put("name", "【服务】"+s.getName());
						map.put("tabIndex", s.getTabIndex());
						map.put("_node_type", "service");
						map.put("_is_leaf", true);
						List<Department> lst2 = departmentManager.find("from Department d where (d.parentDepartment is null or trim(d.parentDepartment.guid)='') and d.service.guid='" + s.getGuid() + "'");
						if(lst2.size()>0){
							map.put("_is_leaf", false);
						}
						jsonList.add(map);
					}
				}else{
					List<Department> lst = null;
					if("service".equals(this.active_node_type)){
						lst = departmentManager.find("from Department d where (d.parentDepartment is null or trim(d.parentDepartment.guid)='') and d.service.guid='" + this.active_node_id + "' order by d.tabIndex asc");						
					}else{
						lst = departmentManager.find("from Department d where d.parentDepartment.guid='" + this.active_node_id + "' order by d.tabIndex asc");
					}
					for(Department d : lst){
						Map map = new HashMap();
						map.put("guid", d.getGuid());
						map.put("parentGuid", this.active_node_id);
						//map.put("serviceGuid", d.getServiceGuid());
						map.put("name", d.getName());
						map.put("tabIndex", d.getTabIndex());
						map.put("_node_type", "department");
						map.put("_is_leaf", true);
						List<Department> lst2 = departmentManager.find("from Department d where d.parentDepartment.guid='" + d.getGuid() + "'");
						if(lst2.size()>0){
							map.put("_is_leaf", false);
						}
						jsonList.add(map);
					}
				}
				
				this.json = JSONUtil.getJsonString(null,null,jsonList);
			}else if("jsonDepartment4ServiceUser".equalsIgnoreCase(this.whichJson)){
				List<Department> lst = departmentManager.find("from Department d where d.service.guid='" + this.getDefaultService().getGuid() + "'");
				this.json = JSONUtil.getJsonString("exclude","parentDepartment,childrenDepartments,employees,service",lst);
			}else if("jsonDepartment4Index".equalsIgnoreCase(this.whichJson)){
				List<Department> lst;
				if(this.node.trim().length()==0){
					lst = departmentManager.find("from Department d where (d.parentDepartment is null or trim(d.parentDepartment.guid)='') and d.service.guid='" + this.source + "'");
				}else{
					lst = departmentManager.find("from Department d where d.parentDepartment.guid='" + this.node + "' and d.service.guid='" + this.source + "'");
				}
				
				List jsonList = new ArrayList();
				for(Department d : lst){
					Map map = new HashMap();
					map.put("guid", d.getGuid());
					map.put("name", d.getName());
					if(d.getTabIndex()==null){
						map.put("tabIndex", 1);
					}else{
						map.put("tabIndex", d.getTabIndex());
					}
					
					jsonList.add(map);
				}
				this.json = JSONUtil.getJsonString(null, null, jsonList);
			}else if("jsonEmployee".equalsIgnoreCase(this.whichJson)){
				Map map = employeeManager.getPagedData("from Employee u where u.department.guid='"+this.node+"'", this.start, this.limit, this.sort, this.dir);
				this.json = JSONUtil.getJsonString("include", "count,list,guid,name,hasOpened,levelGuid,tabIndex", map);
			}
		}catch(Exception e){
			this.json = "[]";
			e.printStackTrace();
		} 

		return AJAX;
	}

	@Action(value="updateDepartmentTabIndex")
	public String updateDepartmentTabIndex() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Department[] ds = (Department[])JSONUtil.stringToArray(json, Department.class);
			for (Department d : ds){
				Department department = (Department)departmentManager.getObject(Department.class, d.getGuid());
				department.setTabIndex(d.getTabIndex());
				departmentManager.saveObject(department);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "更新部门次序成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}
	
	@Action(value="openAccount4Employee")
	public String openAccount4Employee() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			userManager.openManageUserAccounts(this.node);

			ldb.set("success", true);
			ldb.set("reason", "开户成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	@Action(value="openAccount4So")
	public String openAccount4So() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Catalog catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
			String soTypeCode = catalog.getSoType().getCode().trim().toLowerCase();
//			String catalogCode = catalog.getCode().trim().toLowerCase();
			String tableName = catalog.getTableName().trim().toLowerCase();			
			List<Map> lst = dynaBeanManager.getObjects(tableName);
			int tabIndex = 1;
			for (Map map : lst){		
				
				String soInstanceGuid = map.get("item_guid").toString().trim();
				String loginName = map.get("item_code").toString().trim().toLowerCase();
				String userKey = soTypeCode + map.get("item_code").toString().trim().toLowerCase();
				Integer count = userSOManager.getCount("select count(*) from UserSO u where u.so.guid='" + catalog.getGuid() + "' and u.soInstanceGuid='" + soInstanceGuid + "'");
				if(count>0){  //该用户已经开户了，跳过
					continue;
				}else{					
					//String loginName = soTypeCode + map.get("item_code").toString().trim().toLowerCase();
					//String loginName = map.get("item_code").toString().trim().toLowerCase();
					Integer count2 = userManager.getCount("select count(*) from User u where u.userkey='" + userKey + "'");
					if(count2>0){
						log.info(map.get("item_name").toString().trim() + " 的登录名称已经存在！");						
						
						List lstUser = userManager.find("from User u where u.name='" + loginName + "'");
						User user = (User)lstUser.get(0);
						
						List lstUserSO = userSOManager.find("from UserSO u where u.user.guid='" + user.getGuid() + "' and u.so.guid='" + catalog.getGuid() + "' and u.soInstanceGuid='" + soInstanceGuid + "'");						
						if(lstUserSO.size()<1){
							UserSO userSO = new UserSO();
							userSO.setGuid(new GUID().toString());
							userSO.setUser(user);
							userSO.setSo(catalog);
							userSO.setSoInstanceGuid(soInstanceGuid);
							userSO.setTabIndex(new Double(tabIndex));
							userSOManager.saveObject(userSO);
						} 
					}else{
						String userGuid = new GUID().toString();
						User user = new User();
						 
						user.setUserkey(userKey);
						user.setGuid(userGuid);
						user.setName(loginName);
						user.setUserType(User.USERTYPE_ENTERPRISEUSER);
						user.setEnabled(true);
						user.setRealName(map.get("item_name").toString().trim());
						user.setAuthentication_type(1);
						user.setOpenAccountType(3);
						user.setPassword(user.getInitialPassword());
						user.setTabIndex(new Double(tabIndex++));
						userManager.saveObject(user);
						
						UserSO userSO = new UserSO();
						userSO.setGuid(new GUID().toString());
						userSO.setUser(user);
						userSO.setSo(catalog);
						userSO.setSoInstanceGuid(soInstanceGuid);
						userSO.setTabIndex(new Double(tabIndex));
						userSOManager.saveObject(userSO);
					}					
				}				
			}
			
			ldb.set("success", true);
			ldb.set("reason", "开户成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}
	
	@Action(value="openAccount4SoInstance")
	public String openAccount4SoInstance() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Catalog catalog = (Catalog)catalogManager.getObject(Catalog.class, node);// 统计对象类型
			String soTypeCode = catalog.getSoType().getCode().trim().toLowerCase();
			String tableName = catalog.getTableName().trim().toLowerCase();			

			String[] arry = this.source.split(",");
			for(String soInstanceGuid : arry){
				Double tabIndex = new Double(1.0);
				Map<String,Object> map = (Map<String,Object>)dynaBeanManager.getObject(tableName,soInstanceGuid);
				
				/*
				 * 一 .先判断用户名是否重复了，这里暂时不考虑给企业用户自定义用户名，默认的把item_code 当成用户名。
				 */
				
//				String loginName = map.get("item_code").toString().trim().toLowerCase();	
//				Integer countU = userManager.getCount("select count(*) from User u where u.name='" + loginName + "'");
//				   if(countU>0){ 
//						ldb.set("success", false);
//						ldb.set("reason", loginName+"该用户名重复!");
//						this.json = JSONObject.fromObject(ldb).toString();
//						return "openAccount4SoInstance";
//				   }
//				   
			    /*
				 * 二  .判断用户是否开户,有两种方案：
				 * 
				 * 方案一：
			     *   先检查rpt_user表里的userKey是否存在（userkey=soType+item_code，
			     *   用此来表示统计对象的唯一性，即使在不同的统计任务下，如果userkey一样，
			     *   则视为同一对象，同一用户，在rpt_user 里通用一个用户名，在rpt_user_so
			     *   里来区分属于哪个统计任务：
			     *       a.如果userKey不存在，则:rpt_user ,rpt_user_so
			     *         都要插入记录。
			     *       b.如果userkey存在，则表示该统计对象在其他的统计任务下已经开户了，
			     *         只要判断rpt_user_so 中是否有记录了。有则表示已经开户，没有表示在本统计
			     *         任务下没有开户，就在rpt_user_so中插入记录。        
			     *                  
			     * 
			     *			    
			     *  方案二：
			     *    检查rpt_user_so：
			     *      1.如果rpt_user_so有,则表示已经开户了，return "已经开户"
			     *      2.没有表示未开户，先检查rpt_user表里的userKey是否存在（userkey=soType+item_code
			     *            用此来表示统计对象的唯一性，即使在不同的统计任务下，如果userkey一样，
			     *            则视为同一对象，同一用户，在rpt_user 里通用一个用户名，在rpt_user_so
			     *            里来区分属于哪个统计任务.此时分两种情况：
			     *            a.如果userkey存在，则表示该统计对象在其他的统计任务下已经开户了，
			     *              只要判断rpt_user_so 中是否有记录了。有则表示已经开户，没有表示在本统计
			     *              任务下没有开户，就在rpt_user_so中插入记录。  
			     *            b.如果userKey不存在，则:rpt_user ,rpt_user_so 都要插入记录。         
			     */
				   
				String loginName = map.get("item_code").toString().trim().toLowerCase();	
				
	            //此程序按照方案二实现
			    Integer count = userSOManager.getCount("select count(*) from UserSO u where u.so.guid='" + catalog.getGuid() + "' and u.soInstanceGuid='" + soInstanceGuid + "'");
				if(count<1){
					//String loginName = soTypeCode + map.get("item_code").toString().trim().toLowerCase();

					String userKey = soTypeCode + map.get("item_code").toString().trim().toLowerCase();
					
					//查找 rpt_user表里userKey
					Integer count2 = userManager.getCount("select count(*) from User u where u.userkey='" + userKey + "'");
					if(count2>0){ // 表示在rpt_user 表中已经有了username（可能是其他专业已经开户了），则只要向rpt_user_so 中插入记录。				
						
						List lstUser = userManager.find("from User u where u.name='" + loginName + "'");
						User user = (User)lstUser.get(0);
						
						List lstUserSO = userSOManager.find("from UserSO u where u.user.guid='" + user.getGuid() + "' and u.so.guid='" + catalog.getGuid() + "' and u.soInstanceGuid='" + soInstanceGuid + "'");						
						if(lstUserSO.size()<1){
							UserSO userSO = new UserSO();
							userSO.setGuid(new GUID().toString());
							userSO.setUser(user);
							userSO.setSo(catalog);
							userSO.setSoInstanceGuid(soInstanceGuid);
							userSO.setTabIndex(tabIndex);
							userSOManager.saveObject(userSO);
						}
					}else{// 在rpt_user 中没找到 
						String userGuid = new GUID().toString();
						User user = new User();
						
						user.setUserkey(userKey);  
						user.setGuid(userGuid);
						user.setName(loginName);
						user.setUserType(User.USERTYPE_ENTERPRISEUSER);
						user.setEnabled(true);
						user.setRealName(map.get("item_name").toString().trim());
						user.setAuthentication_type(1);
						user.setOpenAccountType(3);
						user.setPassword(user.getInitialPassword());
						user.setTabIndex(tabIndex);
						userManager.saveObject(user);
						
						UserSO userSO = new UserSO();
						userSO.setGuid(new GUID().toString());
						userSO.setUser(user);
						userSO.setSo(catalog);
						userSO.setSoInstanceGuid(soInstanceGuid);
						userSO.setTabIndex(tabIndex);
						userSOManager.saveObject(userSO);
					}					
				}else{// 
	               // 已经开户了。
				}				
			}
			
			ldb.set("success", true);
			ldb.set("reason", "开户成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	@Action(value="insertOrUpdate")
	public String insertOrUpdate() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			User[] ms = (User[])JSONUtil.stringToArray(json, User.class);
			String names = "";

			for (User m : ms){
//				排重
				String sql = "select count(*) from User u where u.name='"+m.getName()+"' and u.guid !='"+m.getGuid()+"'";
				Integer count = userManager.getCount(sql);
				if(count>0){
					names += m.getName() + "\r\n";
				}
			}
			if(names.length()>0){
				ldb.set("success", false);
				ldb.set("valid", false);
				ldb.set("reason", "登录名称重复:\r\n" + names);
				this.json = JSONObject.fromObject(ldb).toString();
				
				return "insertOrUpdate";				
			}
			
			for (User m : ms){
				if(m.getGuid()==null || m.getGuid().trim().length()==0 || m.getGuid().startsWith("NEW")){
					m.setGuid(new GUID().toString());
				}
				userManager.saveObject(m);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="insertOrUpdateDepartment")
	public String insertOrUpdateDepartment() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Department[] ds = (Department[])JSONUtil.stringToArray(json, Department.class);
			for (Department d : ds){
				if(d.getGuid()==null || d.getGuid().trim().length()==0){
					d.setGuid(new GUID().toString());
				}
				//d.setService(this.getDefaultService());
				departmentManager.saveObject(d);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="departmentEdit")
	public String departmentEdit() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Department old = (Department)departmentManager.getObject(Department.class, this.department.getGuid());
			if(old==null){
				old = new Department();
				old.setGuid(this.department.getGuid());
				old.setParentGuid(this.department.getParentGuid());
				//old.setServiceGuid(this.department.getServiceGuid());
			}
			old.setName(this.department.getName());
			departmentManager.saveObject(old);
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			ldb.set("guid", this.department.getGuid());
			ldb.set("parentGuid", this.department.getParentGuid());
			//ldb.set("serviceGuid", this.department.getService().getGuid());
			ldb.set("name", this.department.getName());
						
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="insertOrUpdateEmployee")
	public String insertOrUpdateEmployee() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Department department = (Department) departmentManager.getObject(Department.class, this.node);
			Employee[] ms = (Employee[])JSONUtil.stringToArray(json, Employee.class);
			for (Employee m : ms){
				if(m.getGuid()==null || m.getGuid().trim().length()==0 || m.getGuid().startsWith("NEW")){
					m.setGuid(new GUID().toString());
				}
				m.setDepartment(department);
				//m.setService(department.getService());
				employeeManager.saveObject(m);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="validateField")
	public String validateField() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
//		排重
		String sql = "select count(*) from User u where u.name='"+this.value+"' and u.guid !='"+this.node+"'";
		Integer count = userManager.getCount(sql);
		if(count>0){
			ldb.set("success", true);
			ldb.set("valid", false);
			ldb.set("reason", "登录名称重复。");
			this.json = JSONObject.fromObject(ldb).toString();
		}else{
			ldb.set("success", true);
			ldb.set("valid", true);
			ldb.set("reason", "");
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}
	
	@Action(value="removeUser4catalog")
	public String removeUser4catalog() throws Exception {
		//user = (User)userManager.getObject(User.class, node);
		LazyDynaBean ldb = new  LazyDynaBean();
		
		try{
			userManager.removeObject(User.class, node);
			
			ldb.set("success", true);
			ldb.set("reason", "删除用户成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(DataIntegrityViolationException e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;		
	}
	
	@Action(value="removeDepartment")
	public String removeDepartment() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			departmentManager.removeObject(Department.class, node);
			
			ldb.set("success", true);
			ldb.set("reason", "删除部门成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;		
	}

	@Action(value="removeEmployeeCascade")
	public String removeEmployeeCascade() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			dynaBeanManager.recursiveDeleteForeignKeyData("rpt_employee", node);
			
			ldb.set("success", true);
			ldb.set("reason", "级联删除职员成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;		
	}

	@Action(value="removeEmployee")
	public String removeEmployee() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			employeeManager.removeObject(Employee.class, node);
			
			ldb.set("success", true);
			ldb.set("reason", "删除职员成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(DataIntegrityViolationException e){
			ldb.set("success", false);
			String err = dynaBeanManager.getDataIntegrityViolationExceptionExplain("rpt_employee", node);
			ldb.set("reason", err);
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e) {
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}
		
		return AJAX;		
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setEmployeeManager(EmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getAccounts() {
		return accounts;
	}

	public void setAccounts(String accounts) {
		this.accounts = accounts;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public CatalogManager getCatalogManager() {
		return catalogManager;
	}
 
	public void setCatalogManager(CatalogManager catalogManager) {
		this.catalogManager = catalogManager;
	}

	public HashMap<String, Object> getDynaBean() {
		return dynaBean;
	}

	public void setDynaBean(HashMap<String, Object> dynaBean) {
		this.dynaBean = dynaBean;
	}

	public DynaBeanManager getDynaBeanManager() {
		return dynaBeanManager;
	}

	public void setDynaBeanManager(DynaBeanManager dynaBeanManager) {
		this.dynaBeanManager = dynaBeanManager;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public EmployeeManager getEmployeeManager() {
		return employeeManager;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public DepartmentManager getDepartmentManager() {
		return departmentManager;
	}

	public void setDepartmentManager(DepartmentManager departmentManager) {
		this.departmentManager = departmentManager;
	}

	public UserSOManager getUserSOManager() {
		return userSOManager;
	}

	public void setUserSOManager(UserSOManager userSOManager) {
		this.userSOManager = userSOManager;
	}

	public SoTypeManager getSoTypeManager() {
		return soTypeManager;
	}

	public void setSoTypeManager(SoTypeManager soTypeManager) {
		this.soTypeManager = soTypeManager;
	}
	
	public LevelManager getLevelManager() {
		return levelManager;
	}

	public void setLevelManager(LevelManager levelManager) {
		this.levelManager = levelManager;
	}

	public DbMetaDataManager getDbMetaDataManager() {
		return dbMetaDataManager;
	}

	public void setDbMetaDataManager(DbMetaDataManager dbMetaDataManager) {
		this.dbMetaDataManager = dbMetaDataManager;
	}

	public ApplicationManager getApplicationManager() {
		return applicationManager;
	}

	public void setApplicationManager(ApplicationManager applicationManager) {
		this.applicationManager = applicationManager;
	}

	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	public String getServiceGuid() {
		return serviceGuid;
	}

	public void setServiceGuid(String serviceGuid) {
		this.serviceGuid = serviceGuid;
	}
	
}
